package net.oschina.archx.spring.web;

import net.oschina.archx.spring.entity.User;
import net.oschina.archx.spring.model.JsonModel;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

/**
 * ValidController
 *
 * @author Archx[archx@foxmail.com]
 * @date 2016/2/25 0025
 */
@Controller
@RequestMapping("/valid")
public class ValidController {

    @RequestMapping
    public String index(){
        return "valid";
    }

    @RequestMapping("/submit")
    @ResponseBody
    public JsonModel submit(@Valid User user, BindingResult result){
        JsonModel json = new JsonModel();
        if (result.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError error : errors) {
                sb.append(error.getDefaultMessage()).append(" \n ");
            }
            json.setMessage(sb.toString());
        } else {
            json.setMessage("验证通过");
        }
        return json;
    }
}
